import { ref, onUnmounted, computed } from "vue";
import { getDeviceInfoAPI } from "@/services/badge";
import type { BadgeDeviceInfo } from "@/services/badge/type";
import { useCommonStore } from "@/store/modules/common";
import { showDialog } from "vant";

interface BatteryCheckOptions {
  enableBatteryCheck?: boolean;
  thresholds?: number[]; // 电量阈值数组，从大到小排序
}

export function useDeviceInfo(
  options: BatteryCheckOptions = {
    enableBatteryCheck: false,
    thresholds: [20, 5] // 默认阈值
  }
) {
  const commonStore = useCommonStore();
  const deviceInfo = ref<BadgeDeviceInfo | null>(null);
  const deviceCode = computed(
    () => (commonStore.userInfo as any)?.audioDeviceCode
  );
  let intervalTimer: ReturnType<typeof setInterval> | null = null;
  const preBatteryPer = ref(100);

  // 为每个阈值创建提示状态
  const alertShownStatus = ref<Record<number, boolean>>(
    Object.fromEntries(
      (options.thresholds || []).map(threshold => [threshold, false])
    )
  );

  // 检查电量状态
  function checkBatteryStatus(currentBattery: number, prevBattery: number) {
    if (!options.enableBatteryCheck || !options.thresholds?.length) return;

    // 检查每个阈值
    options.thresholds.forEach(threshold => {
      // 当电量降至阈值以下时触发提示
      if (
        currentBattery <= threshold &&
        prevBattery > threshold &&
        !alertShownStatus.value[threshold]
      ) {
        showBatteryLowDialog(threshold);
        alertShownStatus.value[threshold] = true;
      }

      // 当电量恢复到阈值以上时重置提示状态
      if (currentBattery > threshold) {
        alertShownStatus.value[threshold] = false;
      }
    });
  }

  async function getDeviceInfo() {
    if (!deviceCode.value) {
      deviceInfo.value = null;
      return;
    }
    const data = await getDeviceInfoAPI(deviceCode.value);
    if (data.length === 0) {
      return;
    }
    deviceInfo.value = data[0];

    if (deviceInfo.value) {
      const currentBattery = deviceInfo.value.batteryPer;
      const prevBattery = preBatteryPer.value;

      checkBatteryStatus(currentBattery, prevBattery);
      preBatteryPer.value = currentBattery;
    }
  }

  function showBatteryLowDialog(batteryPer: number) {
    showDialog({
      title: "电量提醒",
      message: `设备电量低于${batteryPer}%，请及时充电！`,
      confirmButtonText: "我知道了"
    }).then();
  }

  async function reloadUserInfo() {
    await (commonStore as any).getUserInfoAction();
    try {
      window.flutter_inappwebview.callHandler("reloadUserInfo");
    } catch (e) {
      console.log("非app端执行，无法与原生进行通讯");
    }
  }

  async function reloadDeviceInfo() {
    await reloadUserInfo();
    if (deviceCode.value) {
      await getDeviceInfo();
    }
  }

  async function startPolling() {
    if (intervalTimer) {
      clearInterval(intervalTimer);
    }

    console.log("startPolling: ", deviceCode.value, commonStore.userInfo);
    await reloadDeviceInfo();

    intervalTimer = setInterval(async () => {
      await reloadDeviceInfo();
    }, 40000);
  }

  onUnmounted(() => {
    if (intervalTimer) {
      clearInterval(intervalTimer);
    }
  });

  return {
    deviceInfo,
    reloadDeviceInfo,
    startPolling
  };
}
